﻿using EasyDDD.Domain;
using Microsoft.EntityFrameworkCore;

namespace EasyDDD.Infrastructure.EFCore.Repository
{
    public static class MediatorExtension
    {
        public static async Task DispatchDomainEventsAsync(this IMediator mediator, DbContext ctx)
        {
            var domainEntities = ctx.ChangeTracker.Entries<IDomainEntity>().Where(e => e.Entity.DomainEvents.Any()).ToList();
            var domainEvents = ctx.ChangeTracker.Entries<IDomainEntity>().SelectMany(e => e.Entity.DomainEvents).ToList();
            foreach (var @entity in domainEntities)
            {
                entity.Entity.ClearDomainEvent();
            }
            foreach (var @event in domainEvents)
            {
                await mediator.Publish(@event);
            }
        }

        //public static async Task PublishDomainEventsAsync(this IMediator mediator, DbContext ctx)
        //{
        //    var domainEvents = ctx.ChangeTracker.Entries<IDomainEntity>().SelectMany(e => e.Entity.DomainEvents);
        //    foreach (var @event in domainEvents)
        //    {
        //        await mediator.Publish(@event);
        //    }
        //}

        public static Task ClearDomainEventsAsync(this IMediator mediator, DbContext ctx)
        {
            var domainEntities = ctx.ChangeTracker.Entries<IDomainEntity>().Where(e => e.Entity.DomainEvents.Any());
            foreach (var @entity in domainEntities)
            {
                entity.Entity.ClearDomainEvent();
            }
            return Task.CompletedTask;
        }
    }
}
